package com.ks.api.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import cn.hutool.Hutool;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ks.api.dto.KsAuthResponse;
import com.ks.api.dto.KsLoginDTO;
import com.ks.api.entity.CultivationLevel;
import com.ks.api.entity.KsConfigSc;
import com.ks.api.entity.KsUser;
import com.ks.api.mapper.CultivationLevelMapper;
import com.ks.api.mapper.KsConfigScMapper;
import com.ks.api.mapper.KsUserMapper;
import com.ks.api.service.KsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class KsUserServiceImpl implements KsUserService {
    
    @Value("${kuaishou.miniapp.appid}")
    private String appId;
    
    @Value("${kuaishou.miniapp.kaifangpingtai_sc}")
    private String appSecret;
    
    @Autowired
    private KsUserMapper ksUserMapper;

    @Autowired
    private CultivationLevelMapper cultivationLevelMapper;
    
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private KsConfigScMapper ksConfigScMapper;
    
    private static final String KS_AUTH_URL = "https://open.kuaishou.com/game/minigame/jscode2session?app_id=%s&app_secret=%s&js_code=%s&grant_type=authorization_code";
    private static final String ALLOWED_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    @Override
    @Transactional
    public KsUser login(KsLoginDTO loginDTO) {

        // 获取软件名称
        String appName = loginDTO.getAppName();
        String url = String.format(KS_AUTH_URL, appId, appSecret, loginDTO.getCode());

        if (StringUtils.equals("zhiyue", appName)) {
            //这是智月
            log.info("智月开始登陆========================================");
            KsConfigSc ksConfigSc = ksConfigScMapper.selectById(2);
            url = String.format(KS_AUTH_URL, ksConfigSc.getKfId(), ksConfigSc.getKfSc(), loginDTO.getCode());
        }else if(StringUtils.equals("chuchuangL", appName)){
            //这是智月
            log.info("初创L开始登陆========================================");
            KsConfigSc ksConfigSc = ksConfigScMapper.selectById(3);
            url = String.format(KS_AUTH_URL, ksConfigSc.getKfId(), ksConfigSc.getKfSc(), loginDTO.getCode());
        }else if(StringUtils.equals("liangFs", appName)){
            //这是智月
            log.info("liangFs开始登陆========================================");
            KsConfigSc ksConfigSc = ksConfigScMapper.selectById(4);
            url = String.format(KS_AUTH_URL, ksConfigSc.getKfId(), ksConfigSc.getKfSc(), loginDTO.getCode());
        }
        // 构建请求URL
        log.info("url ================="+url);
        try {
            // 请求快手API
            String responseStr = HttpUtil.get(url);
            log.debug("快手API返回: {}", responseStr);
            
            // 使用JSONObject手动解析字段
            JSONObject jsonObj = JSON.parseObject(responseStr);
            
            KsAuthResponse authResponse = new KsAuthResponse();
            authResponse.setResult(jsonObj.getInteger("result"));
            authResponse.setMsg(jsonObj.getString("msg"));
            authResponse.setOpenId(jsonObj.getString("open_id"));
            authResponse.setSessionKey(jsonObj.getString("session_key"));
            authResponse.setUnionId(jsonObj.getString("union_id"));
            
            if (authResponse.getResult() != 1) {
                log.error("获取快手用户信息失败: {}", authResponse.getResult());
                throw new RuntimeException("获取快手用户信息失败: " + authResponse.getMsg());
            }
            KsUser existUser = ksUserMapper.findByOpenId(authResponse.getOpenId());
            LocalDateTime now = LocalDateTime.now();

            String nickId = generateRandomId();

            if (existUser != null) {
                KsUser updateUser = new KsUser();
                updateUser.setOpenId(authResponse.getOpenId());
                // 更新会话密钥和登录时间
                ksUserMapper.updateSessionKey(authResponse.getOpenId(), authResponse.getSessionKey(), now);
                if (StringUtils.isBlank(existUser.getNickId())) {
                    updateUser.setNickId(nickId);
                    ksUserMapper.update(updateUser);
                }
                // 如果有用户信息，则更新用户信息
                if (loginDTO.getUserInfo() != null) {
                    updateUser.setNickname(loginDTO.getUserInfo().getNickName());
                    updateUser.setAvatarUrl(loginDTO.getUserInfo().getAvatarUrl());
                    updateUser.setGender(loginDTO.getUserInfo().getGender());
                    updateUser.setCountry(loginDTO.getUserInfo().getCountry());
                    updateUser.setProvince(loginDTO.getUserInfo().getProvince());
                    updateUser.setCity(loginDTO.getUserInfo().getCity());
                    updateUser.setLanguage(loginDTO.getUserInfo().getLanguage());
                    ksUserMapper.update(updateUser);
                }
                
                return ksUserMapper.findByOpenId(authResponse.getOpenId());
            } else {
                // 创建新用户
                KsUser newUser = new KsUser();
                newUser.setOpenId(authResponse.getOpenId());
                newUser.setUnionId(authResponse.getUnionId());
                newUser.setSessionKey(authResponse.getSessionKey());
                newUser.setLastLoginTime(now);
                newUser.setCultivationScore(0);
                newUser.setStatus(1);
                newUser.setNickId(nickId);
                // 如果有用户信息，则设置用户信息
                if (loginDTO.getUserInfo() != null) {
                    newUser.setNickname(loginDTO.getUserInfo().getNickName());
                    newUser.setAvatarUrl(loginDTO.getUserInfo().getAvatarUrl());
                    newUser.setGender(loginDTO.getUserInfo().getGender());
                    newUser.setCountry(loginDTO.getUserInfo().getCountry());
                    newUser.setProvince(loginDTO.getUserInfo().getProvince());
                    newUser.setCity(loginDTO.getUserInfo().getCity());
                    newUser.setLanguage(loginDTO.getUserInfo().getLanguage());
                }
                ksUserMapper.insert(newUser);
                return newUser;
            }
        } catch (Exception e) {
            log.error("快手用户登录异常", e);
            throw new RuntimeException("快手用户登录失败", e);
        }
    }
    
    @Override
    public boolean updateCultivationScore(String openId, Integer score) {
        return ksUserMapper.updateCultivationScore(openId, score) > 0;
    }
    
    @Override
    public KsUser findByOpenId(String openId) {
        return ksUserMapper.findByOpenId(openId);
    }

    @Override
    public void updateUserById(KsUser user) {
        ksUserMapper.updateById(user);
    }

    @Override
    public Map<String, Object> getUserInfoAndLevel(Integer userId) {
        Map<String, Object> map = new HashMap<>();
        KsUser ksUser = ksUserMapper.selectById(userId);
        map.put("user", ksUser);
        LambdaQueryWrapper<CultivationLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.groupBy(CultivationLevel::getMajorStage);
        queryWrapper.select(CultivationLevel::getMajorStage);
        List<CultivationLevel> cultivationLevels = cultivationLevelMapper.selectList(null);
        List<String> collect = cultivationLevels.stream().map(CultivationLevel::getMajorStage).collect(Collectors.toList());
        LambdaQueryWrapper<CultivationLevel> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.orderByAsc(CultivationLevel::getScore);
        List<CultivationLevel> cultivationLevels1 = cultivationLevelMapper.selectList(queryWrapper2);
        CultivationLevel result = new CultivationLevel();
        String currLev = "";
        for (CultivationLevel cultivationLevel : cultivationLevels1) {
            if (cultivationLevel.getScore() > ksUser.getCultivationScore()){
                currLev = cultivationLevel.getMajorStage() +"-"+ cultivationLevel.getMinorStage() +"-"+ cultivationLevel.getMicroStage();
                result = cultivationLevel;
            }
        }
        map.put("cultivationLevels", collect);
        map.put("cultivationLevel", result);
        map.put("currLev", currLev);
        return map;
    }



    public String generateRandomId() {
        String nickId = "";
        //生成一个唯一的nickId
        while (true){
            Random random = new Random();
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                // 从允许的字符集中随机选择一个字符
                int randomIndex = random.nextInt(ALLOWED_CHARACTERS.length());
                char randomChar = ALLOWED_CHARACTERS.charAt(randomIndex);
                sb.append(randomChar);
            }
            String s = sb.toString();
            LambdaQueryWrapper<KsUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(KsUser::getNickId,s);
            List<KsUser> ksUsers = ksUserMapper.selectList(queryWrapper);
            if (ksUsers == null || ksUsers.isEmpty()) {
                nickId = s;
                break;
            }
        }
        return nickId;
    }

} 